<script setup>
import { ref, onMounted } from 'vue'
import { studentService } from '../../services/student'
import DataTable from '../../components/common/DataTable.vue'
import { showSuccess, showError } from '../../utils/message'

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格列配置
const columns = [
  { type: 'index', label: '序号', width: '80', align: 'center' },
  { prop: 'account', label: '账号', width: '120', align: 'center' },
  { prop: 'name', label: '姓名', width: '100', align: 'center' },
  { prop: 'phone', label: '手机号', width: '120', align: 'center' },
  { prop: 'school', label: '学校', width: '120', align: 'center' },
  { prop: 'class', label: '班级', width: '120', align: 'center' },
  { prop: 'teacher', label: '老师', width: '100', align: 'center' },
  { 
    prop: 'isTrialAccount',
    label: '试用账号',
    width: '100',
    align: 'center',
    formatter: (row) => row.isTrialAccount ? '是' : '否'
  },
  {
    slot: 'actions',
    label: '操作',
    width: '200',
    align: 'center',
    fixed: 'right'
  }
]

// 加载学生数据
const loadStudents = async () => {
  try {
    loading.value = true
    const { data, total } = await studentService.getStudentsForCourse({
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize
    })
    tableData.value = data
    pagination.value.total = total
  } catch (error) {
    showError('加载学生数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 处理表格操作
const handleTableAction = async ({ action, row }) => {
  try {
    switch (action) {
      case 'view':
        // TODO: 实现查看功能
        console.log('查看', row)
        break
      case 'assign':
        // TODO: 实现分发功能
        console.log('分发', row)
        break
    }
  } catch (error) {
    showError('操作失败')
    console.error(error)
  }
}

// 监听分页变化
watch(
  () => [pagination.value.currentPage, pagination.value.pageSize],
  () => loadStudents()
)

onMounted(() => {
  loadStudents()
})
</script>

<template>
  <div class="course-assign">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span>课程分配</span>
        </div>
      </template>
      
      <data-table
        v-loading="loading"
        :data="tableData"
        :columns="columns"
        v-model:pagination="pagination"
        @action="handleTableAction"
      >
        <template #actions="{ row }">
          <el-button link type="primary" @click="handleTableAction({ action: 'view', row })">
            查看
          </el-button>
          <el-button link type="primary" @click="handleTableAction({ action: 'assign', row })">
            分发
          </el-button>
        </template>
      </data-table>
    </el-card>
  </div>
</template>

<style scoped>
.page-card {
  margin: 0px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
